package TAIC.IPLM;
import java.io.*;
import java.util.*; 

public class CaleCenter {
	static final int DIM = 128 ; 
	
	public static void main ( String str [] ){
		if ( str.length < 3 ) {
			System.out.println ( "Please input the ori cluster file, the cluster result (train.mat.800) and the number of clusters" ); 
			return ;
		}
		else ( new CaleCenter()).cale ( str[ 0 ], str[ 1 ], Integer.valueOf(str[ 2 ]) ) ; 
	}
	
	public void cale ( String clusterFile, String clusterResult , int totalClusters ) {
		try {
			double center[][]= new double [ totalClusters ][ DIM ] ;
			Scanner clusterScanner = new Scanner ( new File ( clusterFile));
			Scanner resultScanner = new Scanner ( new File ( clusterResult)	) ;
			int vecSize = clusterScanner.nextInt() ; clusterScanner.next() ;
			for ( int i = 0 ; i < vecSize ; i ++ ) {
				double vec [] = new double [ DIM ] ;
				for ( int j = 0 ; j < DIM ; j ++ ) vec [ j ] = clusterScanner.nextInt () ;
				normalize ( vec ) ;
				int clusterNo = resultScanner.nextInt() ;
				for ( int j = 0 ; j < DIM ; j ++ ) center [ clusterNo ][j] += vec [ j ]	 ; 
			}
			for ( int i = 0 ; i < totalClusters ; i ++ ) normalize ( center [ i ] ) ; 
			PrintStream fout = new PrintStream ( new File ( "codebook" ) ) ; 
			fout.println ( totalClusters + " " + DIM ) ; 
			for ( int i = 0 ; i < totalClusters ; i ++ ) {
				for ( int j =0 ; j < DIM ; j ++ ) fout.print ( center [ i ][ j ] + " ") ;
				fout.println () ;
			}
		}	
		catch ( Exception e ) {
			e.printStackTrace() ;
		}
	}
	
	public static void normalize ( double [] vec ) {
		double total = 0 ; 
		for ( int i = 0 ; i < vec.length ;i ++ ) total += vec [ i ] * vec [ i ] ;
		total = Math.sqrt( total ) ;
		for ( int i = 0 ; i < vec.length ; i ++ ) vec [ i ] /= total ; 
	}
	
}
 